<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Log;

class ProductSpecValue extends Base
{

    protected $name = 'product_spec_value';

    public function product()
    {
        return $this->hasOne(Product::class, 'id', 'pid')
            ->field('id,title,price,cate_1,cate_2,icon,stock,status,is_del,business_id,discount_open,freight,limit_num');
    }

    public static function getSettled($param, $user): array
    {
        try {
            $is_prize = isset($param['is_prize']) && $param['is_prize'] == 1 ? 1 : 0;
            if (!$param['num'] || $param['num'] < 1) {
                return ['code' => -1, 'msg' => '购买数量错误'];
            }
            $specValue = parent::where('id', $param['spec_value_id'])->find();
            if (empty($specValue)) {
                return ['code' => -1, 'msg' => '未查询到相关规格'];
            }
            if ($specValue->product->status != 1 || $specValue->product->is_del) {
                return ['code' => -1, 'msg' => '商品已下架'];
            }
            if($specValue->product->limit_num > 0){
                $buys = OrderProduct::where(['uid'=>$user->id, 'pid'=>$specValue->product->id])->count();
                $ordered = OrderTemporary::getOrderedNum($user->id, $specValue->product->id);

                if($buys + $ordered + $param['num'] > $specValue->product->limit_num){
                    return ['code' => -1, 'msg' => '已超出限制购买数量'];
                }
            }
            if ($param['num'] > $specValue->stock) {
                return ['code' => -1, 'msg' => '商品库存不足'];
            }
            //可抵扣账户
            if($is_prize){
                $deductCurrency = $deductChainBean = $deductLoveBean = $deductVipInteg = $deductRedCoin = 0;
            }else{
                $deductCurrency = $user->assets->currency >= $specValue->currency * $param['num'] ? $specValue->currency * $param['num'] : $user->assets->currency;
                $deductChainBean = $user->assets->chain_bean >= $specValue->chain_bean * $param['num'] ? $specValue->chain_bean * $param['num'] : $user->assets->chain_bean;
                $deductLoveBean = $user->assets->love_bean >= $specValue->love_bean * $param['num'] ? $specValue->love_bean * $param['num'] : $user->assets->love_bean;
                $deductVipInteg = $user->assets->vip_integ >= $specValue->vip_integ * $param['num'] ? $specValue->vip_integ * $param['num'] : $user->assets->vip_integ;
                $deductRedCoin = $user->assets->red_coin >= $specValue->red_coin * $param['num'] ? $specValue->red_coin * $param['num'] : $user->assets->red_coin;
            }

            $vip_price = $user->level_id == 1 && in_array($specValue->product->cate_1, [1,8,13]) ? $specValue->price : $specValue->vip_price;//普通会员在VIP区，小爱超市，众道妙方购买使用原价
            $data['product'] = [
                [
                    'business_id'           => $specValue->product->business_id,
                    'business_title'        => $specValue->product->business->title,
                    'business_customer_tel' => $specValue->product->business->customer_tel,
                    'businessFreight'       => $specValue->product->freight * $param['num'],
                    'business_type'         => $specValue->product->business['type'],
                    'business_address'      => $specValue->product->business->full_address,
                    'children'              => [
                        [
                            'pid'           => $specValue->pid,
                            'title'         => $specValue->product->title,
                            'icon'          => $specValue->product->icon,
                            'spec_value_id' => $specValue->id,
                            'vip_price'     => $vip_price,
                            'sku_name'      => SpecItem::getSpecItemName($specValue->sku_id),
                            'num'           => $param['num'],
                            'cate_1'        => $specValue->product->cate_1,
                            'cate_2'        => $specValue->product->cate_2,
                            'business_id'   => $specValue->product->business_id,
                            'currency'      => $deductCurrency,
                            'chain_bean'    => $deductChainBean,
                            'love_bean'     => $deductLoveBean,
                            'vip_integ'     => $deductVipInteg,
                            'red_coin'      => $deductRedCoin,
                            'discount_open' => $specValue->product->discount_open,
                            'discount_list' => UserProductDiscount::getDiscount($user->id, $specValue->pid)
                        ]
                    ]
                ]
            ];

            Log::write(">>>getSettled<<<".json_encode($data['product']));
            $data['total'] = $is_prize ? 0 : $vip_price * $param['num'];
            $data['freightTotal'] = $specValue->product->freight * $param['num'];
            $data['currencyTotal'] = [
                'balance' => $user->assets->currency,
                'usable'  => $deductCurrency
            ];
            $data['chainBeanTotal'] = [
                'balance' => $user->assets->chain_bean,
                'usable'  => $deductChainBean
            ];
            $data['loveBeanTotal'] = [
                'balance' => $user->assets->love_bean,
                'usable'  => $deductLoveBean
            ];
            $data['vipIntegTotal'] = [
                'balance' => $user->assets->vip_integ,
                'usable'  => $deductVipInteg
            ];
            $data['redCoinTotal'] = [
                'balance' => $user->assets->red_coin,
                'usable'  => $deductRedCoin
            ];
            $data['realTotal'] = $is_prize ? 0 : round($data['total'] + $data['freightTotal'] - $deductCurrency - $deductChainBean - $deductLoveBean - $deductVipInteg - $deductRedCoin, 2);
            //定义分区标识
            $data['cate_1'] = [$specValue->product->cate_1];
            $data['cate_2'] = [$specValue->product->cate_2];
            $data['prize_record_id'] = isset($param['prize_record_id']) ? $param['prize_record_id'] : 0;
            return ['code' => 1, 'msg' => 'success', 'data' => $data];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => '服务器错误：' . $e->getMessage()];
        }
    }

    public static function setSpecValue($pid, $data, $business)
    {
        try {
            parent::destroy(['pid' => $pid]);
            $all = [];
            $currency = [];
            $chain_bean = [];
            $vip_integ = [];
            $red_coin = [];
            $give_red_coin = [];
            $love_bean = [];
            $vip_price = [];
            $price = [];
            $profit = [];
            $vip_profit = [];
            $cost = [];
            $stock = 0;
            foreach ($data as $k => $v) {
                $key['sku_id'] = $k;
                $key['pid'] = $pid;
                $key['stock'] = $v['stock'];
                $key['price'] = $v['price'];
                $key['vip_price'] = $v['vip_price'];
                $key['icon'] = $v['icon'];
                if (!$business) {
                    $key['currency'] = $v['currency'];
                    $key['chain_bean'] = $v['chain_bean'];
                    $key['love_bean'] = $v['love_bean'];
                    $key['vip_integ'] = $v['vip_integ'];
                    $key['red_coin'] = $v['red_coin'];
                    $key['give_red_coin'] = $v['give_red_coin'];
                    $key['profit'] = $v['profit'];
                    $key['vip_profit'] = $v['vip_profit'];
                    $key['cost'] = $v['cost'];
                    $currency[] = $v['currency'];
                    $chain_bean[] = $v['chain_bean'];
                    $love_bean[] = $v['love_bean'];
                    $vip_integ[] = $v['vip_integ'];
                    $red_coin[] = $v['red_coin'];
                    $give_red_coin[] = $v['give_red_coin'];
                    $cost[] = $v['cost'];
                    $profit[] = $v['profit'];
                    $vip_profit[] = $v['vip_profit'];
                }
                $all[] = $key;
                $stock += $v['stock'];
                $vip_price[] = $v['vip_price'];
                $price[] = $v['price'];
            }
            (new self())->insertAll($all);
            return [
                'currency'        => $currency ? min($currency) : 0,
                'chain_bean'      => $chain_bean ? min($chain_bean) : 0,
                'love_bean'       => $love_bean ? min($love_bean) : 0,
                'vip_integ'       => $vip_integ ? min($vip_integ) : 0,
                'red_coin'        => $red_coin ? min($red_coin) : 0,
                'give_red_coin'   => $give_red_coin ? min($give_red_coin) : 0,
                'profit'          => $profit ? min($profit) : 0,
                'vip_profit'      => $vip_profit ? min($vip_profit) : 0,
                'cost'            => $cost ? min($cost) : 0,
                'stock'           => $stock,
                'vip_price'       => min($vip_price),
                'price'           => min($price)
            ];
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function getSpecValue($pid, $business = '', $api=false)
    {
        try {

            $list = parent::where('pid', $pid)->select();
            $skuData = [];
            if (!$api) {
                foreach ($list as $v) {
                    $skuData['skus[' . $v['sku_id'] . '][currency]'] = $v['currency'];
                    $skuData['skus[' . $v['sku_id'] . '][chain_bean]'] = $v['chain_bean'];
                    $skuData['skus[' . $v['sku_id'] . '][love_bean]'] = $v['love_bean'];
                    $skuData['skus[' . $v['sku_id'] . '][vip_integ]'] = $v['vip_integ'];
                    $skuData['skus[' . $v['sku_id'] . '][red_coin]'] = $v['red_coin'];
                    $skuData['skus[' . $v['sku_id'] . '][give_red_coin]'] = $v['give_red_coin'];
                    $skuData['skus[' . $v['sku_id'] . '][stock]'] = $v['stock'];
                    $skuData['skus[' . $v['sku_id'] . '][icon]'] = $v['icon'];
                    $skuData['skus[' . $v['sku_id'] . '][price]'] = $v['price'];
                    $skuData['skus[' . $v['sku_id'] . '][vip_price]'] = $v['vip_price'];
                    $skuData['skus[' . $v['sku_id'] . '][profit]'] = $v['profit'];
                    $skuData['skus[' . $v['sku_id'] . '][vip_profit]'] = $v['vip_profit'];
                    $skuData['skus[' . $v['sku_id'] . '][cost]'] = $v['cost'];
                }
            } else {

                foreach ($list as $v) {
                    $sku_id = explode('-', $v['sku_id']);
                    $sku_item = [];
                    foreach ($sku_id as $item) {
                        $sku_item[] = SpecItem::where('id', $item)->value('name');
                    }
                    $skuData[] = [
                        'id'        => $v['id'],
                        'sku_id'    => $v['sku_id'],
                        'sku_item'  => implode('/', $sku_item),
                        'price'     => $v['price'],
                        'vip_price' => $v['vip_price'],
                        'stock'     => $v['stock'],
                        'icon'      => $v['icon']
                    ];
                }
            }

            return $skuData;
        } catch (\Exception $e) {

            return [];
        }
    }
}
